from aiogram import Bot
from fluentogram import TranslatorRunner

from dc_shop.config import Settings
from dc_shop.core.models.enums.order import OrderStatus
from dc_shop.database.services.order import OrderService
from dc_shop.database.services.product import ProductService
from dc_shop.database.services.user import UserService
from dc_shop.tg_bot.keyboards.inline import after_order_kb
from dc_shop.tg_bot.services.locale import Localizator
from dc_shop.tg_bot.services.tg_helpers import send_tg_message
from dc_shop.worker.exception_handler import exception_handler


@exception_handler
async def free_stock_in_cancelled_orders(
    ctx,
) -> None:
    """Возвращает в продажу товары из заказов с отмененной оплатой"""

    bot: Bot = ctx["bot"]
    config: Settings = ctx["config"]
    localizator: Localizator = ctx["localizator"]
    order_service: OrderService = ctx["order_service"]
    user_service: UserService = ctx["user_service"]
    product_service: ProductService = ctx["product_service"]

    cancelled_orders = await order_service.get_expired_payment_orders()

    for order in cancelled_orders:
        order_buyer = await user_service.get_user_by_id(order.buyer_db_id)
        locale: TranslatorRunner = localizator.get_by_locale(order_buyer.lang_code)

        for line in order.order_lines:
            await product_service.increase_product_available_quantity(order.shop_id, line.product_id, line.quantity)
        await order_service.update_order_status(order.id, OrderStatus.cancelled)
        await send_tg_message(
            bot,
            order_buyer.telegram_id,
            locale.get("order-cancelled-msg", order_id=order.id),
            reply_markup=after_order_kb(locale, order.id),
        )
        # TODO Удалять сообщение выше
        await send_tg_message(
            bot,
            config.tg_bot.admin_channel_id,
            locale.get(
                "order-automatically-cancelled-msg",
                order_id=order.id,
            ),
        )


@exception_handler
async def auto_close_completed_orders(ctx):
    """Автоматически закрываем заказы в статусе in_transit"""

    bot: Bot = ctx["bot"]
    config: Settings = ctx["config"]
    localizator: Localizator = ctx["localizator"]
    order_service: OrderService = ctx["order_service"]

    orders = await order_service.get_completed_orders()
    locale: TranslatorRunner = localizator.get_by_locale("ru")

    for order in orders:
        await send_tg_message(
            bot,
            config.tg_bot.admin_channel_id,
            locale.get(
                "order-automatically-closed-msg",
                order_id=order.id,
            ),
        )
        await order_service.update_order_status(order.id, OrderStatus.closed)
